<?php

namespace app\common\library;


use app\common\exception\FailedException;

class HandleSearchParam
{
    //beforeName|afterName,sex     更改键名,一般取值
    /*$condition = [
        ['status',                '=',       'int'],
        ['reserved_phone',        'like',    'like'],
        ['order_sn|order_no',     'like',    'text'],
        ['pay_time|pay_date',     '=',       'time'],
        ['created_at|start_date', 'between', 'bTime'],
    ];
    $params = [
        'order_no'       => "Y20241111111",
        'reserved_phone' => "13253742222",
        'status'     => 1,
        'pay_date'   => "2024-01-11 11:11:25",
        'start_date' => "2024-01-11,2024-01-11 11:11:25",
    ];
    $where = HandleSearchParam::handleSearchParam($params, $condition);
    */
    /**
     * Notes:搜索参数组合
     * @author
     */
    public static function handleSearchParam($params, $condition, $where=[] ) : array
    {
        try {
            foreach($condition as $item){
                //搜索字段名 取值字段名 条件 字段类型
                [$searchField, $valueField, $op, $type] = [$item[0], $item[0], $item[1], $item[2]];
                //取值后搜索字段名|取值前字段名 重新赋值搜索字段名
                if (substr_count($valueField, "|")) {
                    [$searchField, $valueField] = explode("|", $valueField);
                }
                if (isset($params[$valueField]) && (!empty($params[$valueField]) || $params[$valueField] == 0)) {
                    $where[] = [$searchField, $op, self::_getParamsValue($params[$valueField], $type)];
                }
            }
            return $where;
        } catch (\Exception $e){
            throw new FailedException("搜索参数组合失败：".$e->getMessage());
        }
    }

    protected static function _getParamsValue($value, $type)
    {
        switch ($type){
            case 'like':
                $res = '%'.trim($value).'%';
                break;
            case 'text':
                $res = trim($value);
                break;
            case 'int':
                $res = intval($value);
                break;
            case 'time':
                $res = strtotime($value);
                break;
            case 'bTime':
                $data = explode(',', $value);
                if(count($data) != 2){
                    throw new FailedException("搜索时间格式错误");
                }
                $res  = [ strtotime($data[0]), strtotime($data[1]) ];
                break;
            default:
                $res = $value;
                break;
        }
        return $res;
    }
}